import enums.DateTimeFormatterEnum;

import java.time.*;
import java.time.format.DateTimeFormatter;

/**
 * @Author zhangkaiqiang
 * @Date 2019/9/30  11:17
 * @Description JAVA8中的时间处理类
 */
public class LocalDateTimeUtil {


	/**
	 * 得到当前时间
	 * @return
	 */
	public static String getStringNow(){
		LocalDateTime now=LocalDateTime.now();
		return formatLocalDateTime(now, DateTimeFormatterEnum.DEFAULT);
	}


	/**
	 * 按照指定的格式对时间进行格式化为字符串
	 * @param localDateTime
	 * @param pattern
	 * @return
	 */
	public static String  formatLocalDateTime(LocalDateTime localDateTime,DateTimeFormatterEnum pattern){
		return pattern.getDateTimeFormatter().format(localDateTime);
	}


	/**
	 * 字符串转化为时间
	 * @param time
	 * @param pattern
	 * @return
	 */
	public static LocalDateTime stringToLocalDateTime(String time,DateTimeFormatterEnum pattern){
		return LocalDateTime.parse(time,pattern.getDateTimeFormatter());
	}


	/**
	 * 得到两个时间间的间隔时间的秒数
	 * @param t1
	 * @param t2
	 * @return
	 */
	public static long getBetweenTimeToSecond(LocalDateTime t1,LocalDateTime t2){
		ZoneId zone = ZoneId.systemDefault();
		Instant instant=t1.atZone(zone).toInstant();
		Instant instant1=t2.atZone(zone).toInstant();
		return Duration.between(instant,instant1).getSeconds();
	}


	/**
	 * 根据字符串计算两个时间间的相差秒数
	 * @param prev
	 * @param last
	 * @return
	 */
	public static long getBetweenTimeWithString(String prev,String last){
		DateTimeFormatter dateTimeFormatter=DateTimeFormatterEnum.DEFAULT.getDateTimeFormatter();
		LocalDateTime date1=LocalDateTime.parse(prev,dateTimeFormatter);
		LocalDateTime date2=LocalDateTime.parse(last,dateTimeFormatter);
		return getBetweenTimeToSecond(date1,date2);
	}


	/**
	 * 根据毫秒值构建一个LocalDateTime对象
	 */
	public static LocalDateTime timestampToLocalDateTime(long timestamp){
		return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp),ZoneOffset.of("+8"));
	}


	/**
	 * 根据LocalDateTime得到毫秒值
	 */
	private static long localDateTimeToTimeStamp(LocalDateTime localDateTime){
		return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
	}
}
